import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public loginUrl = 'login';
  public redirectUrl = '/admin/statistic';

  constructor(private http: HttpClient, private router: Router) {
  }

  loginIn(loginData): Observable<object> {
    return this.http.post('/auth/login', loginData).pipe(
      tap(() => {
        this.setToken(loginData);
      })
    );
  }

  exit(router: Router): void {
    sessionStorage.removeItem('token');
    this.redirectUrl = router.url;
    this.router.navigateByUrl(this.loginUrl);
  }

  getToken(): string {
    return sessionStorage.getItem('token');
  }

  setToken(token: string): void {
    sessionStorage.setItem('token', token);
  }
}
